package cn.iocoder.yudao.framework.mq.rocketmq.core.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.Environment;


public class RocketMQTopicConfiguration implements BeanPostProcessor {

    @Value("${rocketmq.enhance.enabledIsolation:false}")
    private boolean enabledIsolation;
    @Value("${rocketmq.enhance.environment:}")
    private String environmentName;

//    @Autowired
//    private Environment environment;

    /**
     * 在装载Bean之前实现参数修改
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        if (bean instanceof DefaultRocketMQListenerContainer) {
            DefaultRocketMQListenerContainer container = (DefaultRocketMQListenerContainer) bean;

            //拼接Topic
            if(enabledIsolation && StringUtils.isNoneBlank(environmentName)){
                container.setTopic(String.join("_", container.getTopic(),environmentName));
                container.setConsumerGroup(String.join("_", container.getConsumerGroup(),environmentName));
            }

            return container;
        }
        return bean;
    }

}

